package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceByDayDto;
import com.zzyl.nursing.dto.DeviceByWeekDto;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.job.vo.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.DeviceDataByDayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-29
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 批量保存
     *
     * @param data
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData data) {
        //根据iotId查询设备'
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, data.getHeader().getDeviceId()));
        if(ObjectUtil.isEmpty(device)){
            log.info("设备不存在，设备id：{}",data.getHeader().getDeviceId());
            return;
        }

        //构建设备数据，可能会有多条
        List<IotMsgService> services = data.getBody().getServices();
        if(CollUtil.isEmpty(services)){
            log.info("设备数据为空");
            return;
        }
        //循序services
        services.forEach(s->{

            //处理上报时间
            String eventTimeStr = s.getEventTime();
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(localDateTime);

            List<DeviceData> list = new ArrayList<>();

            s.getProperties().forEach((k,v)->{
                //属性拷贝，从设备拷贝到设备数据
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);
                deviceData.setCreateTime(null);
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v+"");
                deviceData.setAlarmTime(eventTime);
                deviceData.setAccessLocation(device.getBindingLocation());
                list.add(deviceData);
            });
            //批量保存
            saveBatch(list);
            //保存到redis中
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,device.getIotId(), JSONUtil.toJsonStr(list));
        });
    }

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData)?1:0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData)?1:0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    @Override
    public AjaxResult queryDeviceDataListByWeek(DeviceByWeekDto dto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());
        List<DeviceDataByDayVo> list =deviceDataMapper.queryDeviceDataListByWeek(startTime,endTime,dto.getIotId(),dto.getFunctionId());
        log.info("查询结果：{}",list);
        //补全为0时时间段的数据
        list = fillMissingWeeks(list,startTime);
        log.info("补全为0时时间段的数据：{}",list);
        return AjaxResult.success(list);
    }

    /**
     * 按天查询设备心率数据
     * @param dto
     * @return
     */
    @Override
    public AjaxResult queryDeviceDataListByDay(DeviceByDayDto dto) {
        LocalDateTime startTime = LocalDateTimeUtil.of(dto.getStartTime());
        LocalDateTime endTime = LocalDateTimeUtil.of(dto.getEndTime());
        List<DeviceDataByDayVo> list =deviceDataMapper.queryDeviceDataListByDay(startTime,endTime,dto.getIotId(),dto.getFunctionId());
        //补全为0时时间段的数据
        list = fillMissingHours(list);
        return AjaxResult.success(list);
    }

    private List<DeviceDataByDayVo> fillMissingHours(List<DeviceDataByDayVo> list) {
        //创建新的数据集合
        List<DeviceDataByDayVo> result = new ArrayList<>(24);
        //每小时都遍历一次，将数据放入新集合中
        for (int hour = 0; hour < 24; hour++) {
            //将hour转换为对应格式的小时
            String hourTime = String.format("%02d:00", hour);
            DeviceDataByDayVo hourDate = list.stream()
                    //匹配hour对应的list里的时间
                    .filter(data -> hourTime.equals(data.getDateTime()))
                    //拿到匹配的第一个数据
                    .findFirst()
                    // 无数据时创建新的数据对象，value为0最后返回，相当于创建了一个value为0的数据对象
                    .orElse(new DeviceDataByDayVo(hourTime, 0));
            result.add(hourDate);
        }
        return result;
    }
    private List<DeviceDataByDayVo> fillMissingWeeks(List<DeviceDataByDayVo> list, LocalDateTime startTime) {
        //创建新的数据集合
        List<DeviceDataByDayVo> result = new ArrayList<>(7);

        //每小时都遍历一次，将数据放入新集合中
        for (int day = 0; day < 7; day++) {
            //将week转换为对应格式的天数"dateTime":"01.15",
            LocalDate date = startTime.toLocalDate().plusDays(day);
            String dayTime = LocalDateTimeUtil.format(date, "MM.dd");
//            String weekTime = String.format("%02d.%02d", day+1,);
            DeviceDataByDayVo hourDate = list.stream()
                    //匹配hour对应的list里的时间
                    .filter(data -> dayTime.equals(data.getDateTime()))
                    //拿到匹配的第一个数据
                    .findFirst()
                    // 无数据时创建新的数据对象，value为0最后返回，相当于创建了一个value为0的数据对象
                    .orElse(new DeviceDataByDayVo(dayTime, 0));
            result.add(hourDate);
        }
        return result;
    }
    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id)?1:0;
    }

}
